var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var autoprefixer = require('autoprefixer');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var args = require('yargs').argv;

//页面配置
var entrys = [{
  "title": "首页",
  "value": "index"
}];


let exportsData = {
  //公共js（配置api等）
  entry: {
    'vendor': './vendor/vendor.js'
  },
  //输出目录配置
  output: {
    path: path.join(__dirname, 'dist'),
    filename: './pages/[name]/[name].js'
  },

  module: {
    loaders: [{ // css 加载器
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      }, { // 图片打包
        test: /\.(png|jpg|ico|gif)$/,
        loader: 'url-loader', // file-loader也可
        options: {
          limit: 8192,
          publicPath: '/',
          name: "[path][hash:8].[ext]"
        }
      }, { // 字体文件打包
        test: /\.(woff|svg|eot|ttf)\??.*$/,
        loader: 'url-loader?limit=50000&name=[path][name].[ext]'
      }, { // js打包
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader?cacheDirectory',
        options: {
          babelrc: false,
          presets: [
            ['es2015', {
              modules: false
            }]
          ]
        }
      }

    ]
  },
  plugins: [
    new ExtractTextPlugin('./pages/[name]/[name].css'), //配置css 输出目录
    //new webpack.NoErrorsPlugin(),//跳过编译时的错误
    new webpack.DefinePlugin({ // 执行npm run 命令时 __DEV__将为true，执行npm run build命令时 __DEV__将为false
      __DEV__: JSON.stringify(JSON.parse(args.mock || false)),
      'process.env': {
        NODE_ENV: JSON.stringify(JSON.parse(args.mock || false)) ? '"development"' : '"production"'
      }
    }),
    new CopyWebpackPlugin([ //复制文件
      /*
      { from: './html/userHelp.html',to:'html/userHelp.html'}*/
    ])
  ],
  devServer: {
    host: '192.168.0.148', //本机ip
    port: 8898, //默认8080
    inline: true, //可以监控js变化
    hot: true //热启动
  }
}

entrys.forEach(function(item) {
  let folderpath = `./pages/${item.value}/`;
  exportsData.entry[item.value] = `${folderpath}${item.value}.js`;
  exportsData.plugins.push(new HtmlWebpackPlugin({
    hash: true,
    title: item.title,
    filename: `./${folderpath}${item.value}.html`, //输出html目录
    template: `html-withimg-loader!${folderpath}${item.value}.html`, // 页面模板目录
    chunks: ['vendor', item.value],
    chunksSortMode: function(chunk1, chunk2) {
      var orders = ['vendor', item.value];
      var order1 = orders.indexOf(chunk1.names[0]);
      var order2 = orders.indexOf(chunk2.names[0]);
      if (order1 > order2) {
        return 1;
      } else if (order1 < order2) {
        return -1;
      } else {
        return 0;
      }
    },
    minify: {
      removeComments: true,
      collapseWhitespace: true
    }
  }));

});

module.exports = exportsData;